package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        // 先读Redis缓存，如果缓存有，直接返回，如果没有，读数据库，把数据放入redis（缓存重建）
        // dish_分类ID
        String key = "dish_"+dish.getCategoryId();
        Object objList = redisTemplate.opsForValue().get(key);
        if(objList != null){
            log.info("[从redis读取菜品列表].....");
            List<DishVO> dishVOList = (List<DishVO>)objList;
            return dishVOList;
        }
        // 读数据库
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        // 存入redis
        redisTemplate.opsForValue().set(key,dishList);
        log.info("[读取列表]，存入redis....");
        return dishVOList;
    }

    @Resource
    private DishMapper dishMapper;

    @Resource
    private DishFlavorMapper dishFlavorMapper;



    /**
     * 根据id修改菜品基本信息和对应的口味信息
     *
     * @param dishDTO
     */
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //修改菜品表基本信息
        dishMapper.update(dish);

        //删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);
        }

        // 更新了数据库的数据，需要做redis与数据库的缓存一致性【必问】
        // 清空Redis // 搜索key,删除key都是通用命令
        String key = "dish_"+dishDTO.getCategoryId();
        // 数据库，变9.9
        // 删除redis,删除遇到了网络抖动 2S
        redisTemplate.delete(key);

        // 删除成功了，突然出行了高并发，1秒10万单,数据库可能被击垮

    }

    /**
     * 根据id查询菜品和对应的口味数据
     *
     * @param id
     * @return
     */
    public DishVO getByIdWithFlavor(Long id) {
        //根据id查询菜品数据
        Dish dish = dishMapper.getById(id);

        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);//后绪步骤实现

        //将查询到的数据封装到VO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }


    @Transactional(rollbackFor = SQLException.class)
    @Override
    public Integer addDish(DishDTO dishDTO) {
        // 1.新增菜品
        // 把DTO的数据转实体类对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        log.info("[新增菜品前] dish:{}",dish);
        // 公共字段如果使用切面的话，需要在mapper加注解
        Integer tag = dishMapper.insertDish(dish);
        Long dishId = dish.getId();
        log.info("[新增菜品完毕] dishId:{}",dishId);
        // 2.新增菜品口味
        // 获取菜品口味的列表,把当前新插入的菜品ID，赋值每个口味对象
        List<DishFlavor> flavors = dishDTO.getFlavors();
//        for (DishFlavor df:flavors) {
//            df.setDishId(dishId);
//        }
        // -> 箭头函数
        if(flavors!=null && flavors.size()>0){
            flavors.stream().forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
                // 一个一个插入到数据库
                dishFlavorMapper.insert(dishFlavor);
            });
        }
        return tag;
    }

    @Override
    public PageResult findByPage(DishPageQueryDTO dishPageQueryDTO) {
        PageResult pageResult = new PageResult();
        // 分页如何查？
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        List<DishVO> dishVOList = dishMapper.selectByPage(dishPageQueryDTO);
        Page<DishVO> dishVOPage = (Page<DishVO>)dishVOList;
        pageResult.setTotal(dishVOPage.getTotal());
        pageResult.setRecords(dishVOPage.getResult());
        return pageResult;
    }

    @Transactional(rollbackFor = SQLException.class)
    @Override
    public Integer batchDelete( List<Long> ids) {
        // 删除菜品
        Integer tag = dishMapper.deleteByIds(ids);
        // 删除菜品对应的口味
        dishFlavorMapper.deleteByIds(ids);
        return tag;
    }
}
